﻿// --------------------------------------------------------
// <copyright file="DataTablesController.cs" company="ChiakiYu">
//     Copyright (c) 2015-2017 ChiakiYu.All rights reserved
// </copyright >
// <creation-date>2017-03-29 13:46</creation-date>
// <last-editor>于琦(yu_199012@qq.com)</last-editor>
// <last-date>2017-03-29 16:37</last-date>
// --------------------------------------------------------

using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web.Mvc;
using MvcDemo.Models;
using MvcDemo.Models.DataTables;

namespace MvcDemo.Controllers
{
    public class DataTablesController : Controller
    {
        public ActionResult DataTables()
        {
            return PartialView();
        }

        public JsonResult GetDatas(AreaQuery query)
        {
            var data = new Area().GetData();
            if (!string.IsNullOrEmpty(query.Name))
                data = data.Where(n => n.Name.Contains(query.Name));
            if (!string.IsNullOrEmpty(query.Description))
                data = data.Where(n => n.Description.Contains(query.Description));
            if (query.X > 0)
                data = data.Where(n => Equals(n.PointX, query.X));
            if (query.Y > 0)
                data = data.Where(n => Equals(n.PointY, query.Y));

            data = data.OrderBy(query.OrderBy, query.OrderDir == DataTablesOrderDir.Desc);
            var count = data.Count();
            var result = data.Skip(query.Start).Take(query.Length).ToList();

            return DataTablesJson(query.Draw, count, count, result);
        }

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="draw">请求次数计数器</param>
        /// <param name="recordsTotal">总共记录数</param>
        /// <param name="recordsFiltered">过滤后的记录数</param>
        /// <param name="data">数据</param>
        /// <param name="error">服务器错误信息</param>
        public JsonResult DataTablesJson<TEntity>(int draw, int recordsTotal, int recordsFiltered,
            IReadOnlyList<TEntity> data, string error = null)
        {
            var result = new DataTablesResult<TEntity>(draw, recordsFiltered, recordsFiltered, data);
            var jsonResult = new JsonResult
            {
                Data = result
            };
            return jsonResult;
        }
    }
}